import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Card, Row, Col, Spin, Empty, message } from "antd";
import { PlayCircleOutlined } from "@ant-design/icons";
import styles from "./index.module.scss";
import { getVideosApi, type VideoItem } from "../../services/api";

const VideoList = () => {
  const navigate = useNavigate();
  const [videos, setVideos] = useState<VideoItem[]>([]);
  const [loading, setLoading] = useState(true);

  // 从后端 API 获取视频列表
  useEffect(() => {
    const fetchVideos = async () => {
      try {
        setLoading(true);
        const response = await getVideosApi();
        if (response.data) {
          setVideos(response.data);
        }
      } catch (error) {
        console.error("获取视频列表失败:", error);
        message.error(error instanceof Error ? error.message : "获取视频列表失败");
      } finally {
        setLoading(false);
      }
    };

    fetchVideos();
  }, []);

  const handleVideoClick = (videoId: string) => {
    navigate(`/video-detail/${videoId}`);
  };

  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  return (
    <div className={styles.videoListContainer}>
      <h1 className={styles.title}>视频列表</h1>
      {videos.length === 0 ? (
        <Empty description="暂无视频" />
      ) : (
        <Row gutter={[24, 24]}>
          {videos.map((video) => (
            <Col xs={24} sm={12} md={8} lg={6} key={video.id}>
              <Card
                hoverable
                className={styles.videoCard}
                cover={
                  <div className={styles.thumbnailContainer}>
                    <img
                      alt={video.title}
                      src={video.thumbnail}
                      className={styles.thumbnail}
                    />
                    <div className={styles.playOverlay}>
                      <PlayCircleOutlined className={styles.playIcon} />
                    </div>
                    {video.duration && (
                      <div className={styles.duration}>{video.duration}</div>
                    )}
                  </div>
                }
                onClick={() => handleVideoClick(video.id)}
              >
                <Card.Meta
                  title={<div className={styles.videoTitle}>{video.title}</div>}
                  description={
                    video.description && (
                      <div className={styles.videoDescription}>
                        {video.description}
                      </div>
                    )
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      )}
    </div>
  );
};

export default VideoList;
